/*
 * edbd_elect.c - EDBD Inter-Connection - Master Election
 * Clunix, glory@clunix.com, yjlee@clunix.com, 2001.8.22.
 * Clunix, cezanne@clunix.com, yjlee@clunix.com, 2005.4
 *
 * Copyright (c) 2001-2005 by Clunix Inc. All Rights Reserved.
 */

#include "config.h"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "edbd.h"
#include "edb.h"
#include "edb_proto.h"
#include "eds.h"
#include "reactor.h"
#include "edbroot.h"

ECM_INLINE sr_t *
get_cluster(const char *clname)
{
	sr_t	*sr_clusters, *sr_cluster;

	sr_clusters = edbroot_getc(sr_edbroot, "clusters");
	if (clname == NULL)
		sr_cluster = edbroot_getc(sr_clusters, self_clname);
	else
		sr_cluster = edbroot_getc(sr_clusters, clname);
	tree_unlock(sr_clusters, PIN_LOCK);
	return sr_cluster;
}

ECM_INLINE sr_t *
get_node(const char *clname, const char *ndname)
{
	sr_t	*sr_cluster, *sr_nodes, *sr_node;

	sr_cluster = get_cluster(clname);
	sr_nodes = edbroot_getc(sr_cluster, "nodes");
	tree_unlock(sr_cluster, PIN_LOCK);

	if (ndname == NULL)
		sr_node = edbroot_getc(sr_nodes, self_ndname);
	else
		sr_node = edbroot_getc(sr_nodes, ndname);
	tree_unlock(sr_nodes, PIN_LOCK);

	return sr_node;
}

void
add_node(edbd_conn_t edbd_conn, const char *clname, const char *ndname)
{
	sr_t	*sr_cluster;
	sr_t	*sr_nodes, *sr_node, *sr_status;

	sr_cluster = get_cluster(clname);
	sr_nodes = edbroot_getc(sr_cluster, "nodes");
	tree_unlock(sr_cluster, PIN_LOCK);

	sr_node = conn_xecreate(edbd_conn, sr_nodes, ndname, ST_NULL, 0, ECM_TRUE);
	if (sr_node == NULL) {
		tree_unlock(sr_nodes, PIN_LOCK);
		return;
	}
	sr_status = edbroot_getc(sr_node, "status");
	conn_set_asrv(edbd_conn, sr_status, "up");
	tree_unlock(sr_status, PIN_LOCK);
	tree_unlock(sr_node, PIN_LOCK);
	tree_unlock(sr_nodes, PIN_LOCK);
}

ECM_INLINE void
del_node(edbd_conn_t edbd_conn, const char *clname, const char *ndname)
{
	sr_t	*sr_node;

	sr_node = get_node(clname, ndname);
	if (sr_node == NULL)
		return;
	conn_xedelete(edbd_conn, sr_node, ECM_TRUE, ECM_FALSE);
}

ECM_INLINE ECMBOOL
add_cluster(edbd_conn_t edbd_conn, const char *clname)
{
	sr_t	*sr_clusters, *sr_cluster;

	sr_clusters = edbroot_getc(sr_edbroot, "clusters");
	sr_cluster = conn_xecreate(edbd_conn, sr_clusters, clname, ST_NULL, 0, ECM_TRUE);
	if (sr_cluster == NULL) {
		tree_unlock(sr_clusters, PIN_LOCK);
		return ECM_FALSE;
	}
	tree_unlock(sr_cluster, PIN_LOCK);
	tree_unlock(sr_clusters, PIN_LOCK);
	return ECM_TRUE;
}

ECM_INLINE void
del_cluster(edbd_conn_t edbd_conn, const char *clname)
{
	sr_t	*sr_cluster;

	sr_cluster = get_cluster(clname);
	if (sr_cluster == NULL)
		return;
	conn_xedelete(edbd_conn, sr_cluster, ECM_TRUE, ECM_FALSE);
}
